package com.dfbz.controller;

import com.alibaba.fastjson.JSON;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

public class BaseServlet extends HttpServlet {
    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        response.setCharacterEncoding("utf-8");
        String uri = request.getRequestURI();
        uri = uri.substring(uri.lastIndexOf("/") + 1);
        Class<? extends BaseServlet> aClass = this.getClass();
        try {
            Method method = aClass.getDeclaredMethod(uri, HttpServletRequest.class, HttpServletResponse.class);
            method.invoke(this,request,response);
        } catch (Exception e) {

        }
    }

    protected Map<String,String> getParam(HttpServletRequest request){
        Map<String, String> resultMap = new HashMap<>();
        Map<String, String[]> map = request.getParameterMap();
        for (String key : map.keySet()) {
            String[] values = map.get(key);
            if(map.get(key).length > 1){
                String val = Arrays.toString(values);
                resultMap.put(key,val);
            }else{
                resultMap.put(key,values[0]);
            }
        }
        return resultMap;
    }

    protected void writeObjectToString(HttpServletResponse response,Object obj){
        response.setContentType("application/json;charset=utf8");
        String objJson = JSON.toJSONString(obj);
        try {
            response.getWriter().write(objJson);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}
